package com.keya.utils;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUnit;

import java.util.Set;

/**
 * 本地缓存.
 *
 * @author : xf.he
 * @version : 1.0 2023/4/19
 * @since : 1.0
 **/
public class LocalCache {

    /**
     * 默认缓存时长 10s
     */
    private static final long DEFAULT_TIMEOUT = 10 * DateUnit.SECOND.getMillis();
    /**
     * 默认清理间隔时间 1m
     */
    private static final long CLEAN_TIMEOUT = DateUnit.MINUTE.getMillis();
    /**
     * 缓存对象
     */
    private static final TimedCache<String, Object> TIMED_CACHE = CacheUtil.newTimedCache(DEFAULT_TIMEOUT);

    static {
        //启动定时任务
        TIMED_CACHE.schedulePrune(CLEAN_TIMEOUT);
    }

    public static void set(String key, Object value) {
        TIMED_CACHE.put(key, value);
    }

    public static void set(String key, Object value, long expire) {
        TIMED_CACHE.put(key, value, expire);
    }

    /**
     * 获取并重新计算过期时间
     */
    public static Object getWithUpdateLastAccess(String key) {
        return TIMED_CACHE.get(key);
    }

    /**
     * 获取
     */
    public static Object get(String key) {
        return TIMED_CACHE.get(key, false);
    }

    public static Set<String> keySet() {
        return TIMED_CACHE.keySet();
    }


    public static void remove(String key) {
        TIMED_CACHE.remove(key);
    }

    public static void clear() {
        TIMED_CACHE.clear();
    }

}
